/**
 *
 */
package com.iot.ic.modules.web;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iot.ic.common.web.BaseController;
import com.iot.ic.modules.model.User;
import com.iot.ic.modules.service.UserService;

/**
 * @author haojinyu 医生
 */
@Controller
public class UserController extends BaseController {
	final static int patientType = 0;
	final static int doctorType = 1;
	@Autowired
	private UserService userService;

	@RequestMapping("/doctor/register")
	@ResponseBody
	public Map<String, Object> doctorRegister(HttpServletRequest request, User user) {
		if (StringUtils.isEmpty(user.getHospital())) {
			return packInfo(false, "组织机构为空，注册", "hospital");
		}
		if (StringUtils.isEmpty(user.getDept())) {
			return packInfo(false, "单位部门为空，注册", "dept");
		}
		if (StringUtils.isEmpty(user.getCertNo())) {
			return packInfo(false, "证书编号为空，注册", "certNo");
		}
		user.setUserType(1);
		return register(request, user);
	}

	@RequestMapping("/doctor/update")
	@ResponseBody
	public Map<String, Object> doctorUpdate(HttpServletRequest request, User user) {
		user.setUserType(1);
		return update(user);
	}

	@RequestMapping("/doctor/findDr")
	@ResponseBody
	public Map<String, Object> findDr(HttpServletRequest request, Integer id, String name, String hospital) {
		try {
			List<User> list = userService.findUser(id, name, hospital, doctorType);
			return packData(list);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/patient/findPatient")
	@ResponseBody
	public Map<String, Object> findPatient(HttpServletRequest request, Integer id, String name) {
		try {
			List<User> list = userService.findUser(id, name, null, 0);
			return packData(list);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/patient/update")
	@ResponseBody
	public Map<String, Object> patientUpdate(HttpServletRequest request, User user) {
		user.setUserType(patientType);
		return update(user);
	}

	@RequestMapping("/patient/register")
	@ResponseBody
	public Map<String, Object> patientRegister(HttpServletRequest request, User user) {
		user.setUserType(patientType);
		return register(request, user);
	}

	@RequestMapping("/patient/updateXiaomiRegId")
	@ResponseBody
	public Map<String, Object> pUpdateXiaomiRegId(Integer userId, String mRegId) {
		return updateXiaomiRegId(userId, mRegId);
	}

	@RequestMapping("/doctor/updateXiaomiRegId")
	@ResponseBody
	public Map<String, Object> dUpdateXiaomiRegId(Integer userId, String mRegId) {
		return updateXiaomiRegId(userId, mRegId);
	}

	@RequestMapping("/doctor/login")
	@ResponseBody
	public Map<String, Object> doctorLogin(String userName, String password) {
		return login(userName, password, 1);
	}

	@RequestMapping("/weblogin")
	public ModelAndView webLogin(String userName, String password) {
		Map<String, Object> map = login(userName, password, 2);
		if (map.get("result").equals(0)) {
			return new ModelAndView("/doctor/index").addAllObjects(map);
		} else {
			return new ModelAndView("/login").addAllObjects(map);
		}
	}

	@RequestMapping("/patient/login")
	@ResponseBody
	public Map<String, Object> patientLogin(String userName, String password) {
		return login(userName, password, 0);
	}

	public Map<String, Object> login(String userName, String password, int userType) {
		if (StringUtils.isEmpty(userName)) {
			return packInfo(false, "用户名或手机为空，登录");
		}
		if (StringUtils.isEmpty(password)) {
			return packInfo(false, "密码为空，登录");
		}
		User dr = null;
		try {
			dr = userService.findByNameOrMobile(userName, userType);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
		if (dr != null) {
			String pwdMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
			if (dr.getDelStatus() != 0) {
				return packInfo(false, "该用户已被删除，登录");
			} else if (dr.readPassword().equals(pwdMd5)) {
				Map<String, Object> map = packInfo(true, "登录");
				map.put("data", dr);
				return map;
			} else {
				return packInfo(false, "密码错误，登录");
			}
		} else {
			return packInfo(false, "该用户不存在，登录");
		}
	}

	/**
	 * 注册
	 *
	 * @param user
	 *            用户
	 * @return json
	 */
	public Map<String, Object> register(HttpServletRequest request, User user) {
		if (StringUtils.isEmpty(user.getUserName())) {
			return packInfo(false, "用户名为空，注册");
		}
		if (StringUtils.isEmpty(user.getTrueName())) {
			return packInfo(false, "真实姓名为空，注册");
		}
		if (StringUtils.isEmpty(user.getMobile())) {
			return packInfo(false, "手机号码为空，注册");
		}
		if (StringUtils.isEmpty(user.readPassword())) {
			return packInfo(false, "密码为空，注册");
		}
		if (StringUtils.isEmpty(user.getIdcard())) {
			return packInfo(false, "身份证号码为空，注册");
		}
		try {
			if (userService.findByMobile(user.getMobile(), user.getUserType()) != null) {
				return packInfo(false, "该手机已注册，注册");
			}
			if (userService.findByName(user.getUserName(), user.getUserType()) != null) {
				return packInfo(false, "用户名已被注册，注册");
			}
			String pwdMd5 = DigestUtils.md5DigestAsHex(user.readPassword().getBytes());
			user.setPassword(pwdMd5);
			user.setDelStatus(0);
			user.setAddtime(new Date());
			User patient2 = userService.saveOrUpdateObject(user);
			boolean success = savePic(patient2, request);
			if (success) {
				Map<String, Object> map = packInfo(true, "注册");
				map.put("data", patient2);
				return map;
			} else {
				Map<String, Object> map = packInfo(false, "图片上传失败，注册");
				userService.deleteUserById(patient2);
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 保存图片
	 *
	 * @param user
	 * @param request
	 */
	private boolean savePic(User user, HttpServletRequest request) {
		try {
			List<String> idcardList = springUpload(request, user.getTrueName(), "idCardImg");
			if (idcardList == null || idcardList.size() == 0) {
				return false;
			}
			user.setIdcardUrl(idcardList.get(0));
			if (user.getUserType() == 1) {
				List<String> certList = springUpload(request, user.getTrueName(), "certImg");
				if (certList == null || certList.size() == 0) {
					return false;
				}
				user.setCertUrl(certList.get(0));
			}
			userService.saveOrUpdateObject(user);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 修改
	 *
	 * @param user
	 *            用户
	 * @return json
	 */
	public Map<String, Object> update(User user) {
		if (user.getId() == 0) {
			return packInfo(false, "用户编号为空，保存");
		}
		try {
			User u = (User) userService.updateUser(user);
			if (u != null) {
				Map<String, Object> map = packInfo(true, "保存");
				map.put("data", u);
				return map;
			} else {
				return packInfo(false, "未知错误，保存");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/uploadpic")
	@ResponseBody
	public Map<String, Object> update(HttpServletRequest request) {
		try {
			List<String> a = springUpload(request, "张三", "idcard");
			List<String> b = springUpload(request, "张三", "drcert");
			List<String> c = springUpload(request, "张三", "case");
			System.out.println("a.size()=" + a.size() + " b.size()=" + b.size() + " c.size()=" + c.size());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return packInfo(true, "success");
	}

	public Map<String, Object> updateXiaomiRegId(Integer userId, String mRegId) {
		if (StringUtils.isEmpty(userId)) {
			return packInfo(false, "用户编号为空，注册", "userId");
		}
		if (StringUtils.isEmpty(mRegId)) {
			return packInfo(false, "小米注册编号为空，注册", "mRegId");
		}
		try {
			boolean success = userService.updateUserRegId(userId, mRegId);
			return packInfo(success, "updateXiaomiRegId ");
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}
}
